/*
    Project:        Home Power Control
    File:           HPCRainGauge.cpp
    Author:         christian@karunamusic.at
    Date:           11.2014
    Description:    Sensor to measure the amount of rain in l/m2.
                    The sensor gives one tick per 0,2794mmwater in the sensor.
                    1mm is aequivalent to 1 l/m2.
 */

#include <unistd.h>
#include <limits>
#include <iostream>
#include <wiringPi.h>
#include "globals.h"
#include "HPCRainGauge.h"

using namespace std;

unsigned int HPCRainGauge::m_Counter = 0;
boost::mutex rmtx;

HPCRainGauge::HPCRainGauge( unsigned long id, unsigned int pin, unsigned int interval )
    : HPCThreadedSensor(id, pin, interval)
{
    PROFILE_THIS;

    m_Old = 0.0f;
    digitalWrite( m_Pin, HIGH );
    wiringPiISR( m_Pin, INT_EDGE_FALLING, &isr );
}

HPCRainGauge::~HPCRainGauge()
{
    PROFILE_THIS;
}

void HPCRainGauge::isr()
{
    PROFILE_THIS;

    rmtx.lock();
    m_Counter++;
    rmtx.unlock();
}

void HPCRainGauge::Measure()
{
    PROFILE_THIS;

    // 1 tick == 0.2794mm, 1mm == 1l/m2
    m_Value = ((((float)m_Counter * 28.0f) / 10.0f) / (float)m_Time) / 3.5f;
    float scale = 0.1f;
    m_Value = floor((float)m_Value / scale + 0.5f) * scale;
}

bool HPCRainGauge::hasChanged()
{
    PROFILE_THIS;

    Measure();
    LOG( debug, "Measured value: " << (string)m_Value << " " << MeasureUnit() );

    rmtx.lock();
    m_Counter = 0;
    rmtx.unlock();

    return (m_Value != m_Old);
}

int HPCRainGauge::isAlarm()
{
    unsigned int tmp = m_Counter;
    unsigned int mTime = 1;

    sleep(mTime); // count ticks for at least 1sec !

    tmp = m_Counter - tmp; // get the ticks of the last second.

    m_Value = ((((float)tmp * 28.0f) / 10.0f) / 3.5f) / (float)mTime;
    float scale = 0.1;
    m_Value = floor((float)m_Value / scale + 0.5f) * scale;

    return m_Value.isAlarm();
}
